﻿using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Discovery;
using System;
using System.Configuration;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.ServiceModel.Description;

namespace AdvanceGridSearchCrm2013
{
    public class OrgnizationServiceHandler
    {

        private static bool AcceptAllCertificatePolicy(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }

        public static IOrganizationService GetService()
        {
            Uri organizationUri = new Uri(ConfigurationManager.AppSettings.Get("CRMWOrgUrl"));
            Uri discoveryUri = new Uri(ConfigurationManager.AppSettings.Get("CRMWDiscoveryUrl"));
            string username = ConfigurationManager.AppSettings.Get("CrmUserName");
            string password = ConfigurationManager.AppSettings.Get("CRMUserPass");
                
            //to ignore certificates errors
            ServicePointManager.ServerCertificateValidationCallback = AcceptAllCertificatePolicy;

            ClientCredentials userCredentials = new ClientCredentials();
            userCredentials.UserName.UserName = username;
            userCredentials.UserName.Password = password;

            IServiceConfiguration<IDiscoveryService> discoveryConfiguration = ServiceConfigurationFactory.CreateConfiguration<IDiscoveryService>(discoveryUri);
            var _discServiceProxy = new DiscoveryServiceProxy(discoveryConfiguration, userCredentials);
            _discServiceProxy.Timeout = new TimeSpan(10, 2, 2);
            
            IServiceConfiguration<IOrganizationService> serviceConfiguration = ServiceConfigurationFactory.CreateConfiguration<IOrganizationService>(organizationUri);
            var serviceProxy = new OrganizationServiceProxy(serviceConfiguration, userCredentials);
            serviceProxy.EnableProxyTypes();
            serviceProxy.Timeout = new TimeSpan(10, 2, 2);
          
            IOrganizationService service = (IOrganizationService)serviceProxy;
           
            return service;

        }
    }
}
